package com.foosun.core.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.foosun.core.base.PageData;
import com.foosun.core.entity.SysConfig;
import com.foosun.core.entity.validator.SysConfigValidator;
import com.foosun.core.service.SysConfigService;

/**
 * Created by Leo on 14-8-16.
 */
@Controller
@RequestMapping("/core/sysConfig")
public class SysConfigAction {

    @Autowired
    private SysConfigService sysConfigService;

    @RequestMapping("/list")
    public String list(Model model, PageData<SysConfig> pageData, HttpServletRequest request) throws Exception {
        pageData.setWebMap(request.getParameterMap());
        pageData = sysConfigService.findList(pageData);
        model.addAttribute("pageData", pageData);
        return "/oa/sysConfig/list";
    }

    @RequestMapping("/new")
    public String form(Model model) throws Exception {
    	SysConfig sysConfig = new SysConfig();
    	model.addAttribute(sysConfig);
    	

        return "/oa/sysConfig/input";
    }
    
    @RequestMapping("/edit/{id}")
    public String edit(Model model, @PathVariable("id") Integer id) throws Exception {
    	SysConfig sysConfig = sysConfigService.findById(id);
        model.addAttribute(sysConfig);
        

        return "/oa/sysConfig/input";
    }


    @RequestMapping("/save")
    public String save(@ModelAttribute("sysConfig") SysConfig sysConfig, Errors errors, Model model) throws Exception {

    	String view = null;
		if (!errors.hasErrors()) {
			ValidationUtils.invokeValidator(new SysConfigValidator(), sysConfig,
					errors);
			if(errors.hasErrors()){
				model.addAllAttributes(errors.getAllErrors());
				model.addAttribute(sysConfig);
				view = "/oa/sysConfig/input";
			}else{
				view = "redirect:/core/sysConfig/list";
				sysConfigService.save(sysConfig);
			}
		}
		return view;
    }

    @RequestMapping("/delete/{id}")
    public String deleteAll(Model model, @PathVariable("id") Integer id) throws Exception {
    	sysConfigService.delete(id);
        return "redirect:/core/sysConfig/list";
    }
    
}
